import os
from django.shortcuts import render, reverse, redirect
from django.views.decorators.http import require_POST, require_GET
from django.views.generic import View, ListView, DetailView
from minefieldplatform.settings import BASE_DIR
from django.http import JsonResponse
from django.template import loader
from .models import Task
from pure_pagination import PaginationMixin
from django.db.models import Q
from django_redis import get_redis_connection
from .task import task_execute

redis_cli = get_redis_connection('default')


class TaskAddView(View):
    @staticmethod
    def get(request):
        return render(request, 'task/generaltask_add.html')

    @staticmethod
    def post(request):
        host = request.POST.get('host')
        content = request.POST.get('content')
        name = request.POST.get('name')

        task = Task()
        task.name = name
        task.content = content
        task.dest_hosts = host
        task.save()
        return JsonResponse({'code': 0, 'msg': '任务创建成功'})


class TaskListView(PaginationMixin, ListView):
    """
    任务列表
    """
    template_name = 'task/task_list.html'
    model = Task
    paginate_by = 10
    keyword = None

    def get_keyword(self):
        self.keyword = self.request.GET.get('keyword')
        return self.keyword

    def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.order_by("-created_at")
        keyword = self.get_keyword()
        if keyword:
            queryset = queryset.filter(Q(name__icontains=keyword) | Q(dest_hosts__icontains=keyword) |
                                       Q(content__icontains=keyword) | Q(created_at__month=keyword) |
                                       Q(created_at__day=keyword))
        return queryset

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['keyword'] = self.keyword
        return context


class TaskCancelView(View):

    @staticmethod
    def get(request, pk):
        task = Task.objects.filter(id=pk).get()
        task.status = 2
        task.save()
        # return reverse('task:task_list')
        # response = HttpResponse('取消成功')
        print(pk)
        return redirect(reverse('task:task_detail', args=[pk]))

    @property
    def get_success_url(self):
        return reverse('task:task_list')


class TaskDetailView(DetailView):
    """
    任务详情页
    """
    template_name = 'task/task_detail.html'
    model = Task

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['prev'] = self.request.GET.get('prev')
        return context


@require_POST
def get_playbook(request):
    host = request.POST.get('host', '')
    content = request.POST.get('content', '')
    if content:
        with open(os.path.join(BASE_DIR, 'tmp', 'tmp_playbook.yml'), 'w') as f:
            f.write(content)
        with open(os.path.join(BASE_DIR, 'tmp', 'tmp_playbook.yml'), 'r') as f:
            content = ''
            for line in f:
                if line.startswith('- hosts'):
                    content += '- hosts: \'{}\'\n'.format(host)
                else:
                    content += line
    else:
        content = loader.render_to_string(
            'task/playbook_demo.yml.template', {'dest_hosts': host})
    return JsonResponse({'code': 0, 'msg': '获取Playbook demo成功!', 'content': content})


@require_POST
def task_publish(request, pk):
    """
    发布任务
    :param request:
    :param pk
    :return:
    """
    # 发布任务  状态流转
    # historic_task = HistoricTask.objects.filter(id=pk).get()
    # historic_task.status = 3
    # historic_task.publisher = request.user
    # historic_task.publish_at = timezone.now()
    # historic_task.save()
    # 任务执行
    # task = Task.objects.get(id=historic_task.task_id)
    # task.dest_hosts.set([host.id for host in historic_task.dest_hosts.all()])
    # task.content = historic_task.content
    # 同步执行
    task_execute(pk)
    # task.save()
    return JsonResponse({'code': 0, 'msg': '已将任务放到后台执行，请稍后！'})


@require_GET
def get_task_result(request):
    """
    发布配置文件结果
    :param request:
    :return:
    """
    task_id = request.GET.get('task_id')
    redis_key_prefix = 'ark::task'
    data = redis_cli.get('{}::{}'.format(redis_key_prefix, task_id))
    if not data:
        data = "任务开始执行，请稍作等待！"
    else:
        data = str(data, encoding='utf8')
    return JsonResponse({'code': 0, 'data': data})
